package sisi.yacht;

import java.security.cert.Certificate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.CreateEvent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zk.ui.sys.ComponentsCtrl;
import org.zkoss.zk.ui.util.ConventionWires;
import org.zkoss.zul.Button;
import org.zkoss.zul.Doublebox;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.Window;

import sisi.General;
import sisi.bank.Bank;
import sisi.bank.BankController;
import sisi.corporation.Corporation;
import sisi.corporation.CorporationController;


/**
 * YachtsWindow.java - Controller class for <i>Yachts window</i>. 
 * @author Pedro Gonzalez pedro@sisisoftware.it
 * @author Claudio Pelosi claudio@sisisoftware.it
 * @author SISI Software S.n.c. - www.sisisoftware.it
 * @version 1.0, 26/09/2013
 * 
 */

@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
public class YachtsWindow extends Window implements
		org.zkoss.zk.ui.ext.AfterCompose {
	
	// listbox boxYachts
	private Window windowYachts;
	private Textbox tbCerca;
	private Listbox boxYachts;
	@SuppressWarnings("rawtypes")
	private List tutti_gli_yachts;
	private boolean lNuovo;
	private Toolbarbutton buttonSeleziona, buttonNuovo, buttonModifica,
			buttonCancella, buttonStampa, buttonExcel;

	private ListModelList listModelList;
	private String cerca = "";
	
	// edit yacht
	private Window windowEditYacht;
	private Intbox id;
	private Textbox name, boatgsm, corporation, captain, captgsm, vesstype, fiscalstatus, chiefeng, chiefgsm, loam, wum, dum;
	private Textbox fuelconnection, cum, enginetype, enginenumb, pumpingrate, othercontact1, othercontact2, oilused;
	private Textbox shipyard, portofreg, flag, email, satcomtel, satcomfax, callsign, gsm, bank, payment, note;
	private Doublebox loa, beam, draft, grton, nettonage;
	private Intbox fueltankcapacity, corpid;
	private Listbox bankreceivable;
	private Object yachtItem;
	private Anayacht modYacht;
	
	protected Map<String, Object> args;

	public void onCreate$windowYachts(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		boolean lTastoSeleziona = (Boolean)args.get("tastoSeleziona");
		if (!lTastoSeleziona) {
			// buttonSeleziona.setVisible(false);
		}

		listModelList = new ListModelList();
		tutti_gli_yachts = new AnayachtController().getAnayachtList(null);
		listModelList.addAll(tutti_gli_yachts);
		boxYachts.setModel(listModelList);
		boxYachts.setItemRenderer(new YachtsItemRenderer());

	}

	public void afterCompose() {

		// wire variables
		ConventionWires.wireVariables(this, this);

		// auto forward
		ConventionWires.addForwards(this, this);

	}

	
	public void onOK$tbCerca(Event event){
		cerca();
	}
	
	public void onClick$buttonCerca(Event event) {
		cerca();
	}
	
	
	private void cerca(){
		listModelList = new ListModelList();
		tutti_gli_yachts = new AnayachtController().getAnayachtList(tbCerca
				.getValue());
		listModelList.addAll(tutti_gli_yachts);
		boxYachts.setModel(listModelList);
		boxYachts.setItemRenderer(new YachtsItemRenderer());		
	}
	
	
	
	public void onDoubleClicked(Event event) throws Exception {
		//if (buttonSeleziona.isVisible()) {
			modifica(false);

	}
	
	public void onClick$buttonNuovo(Event event){
		modifica(true);
	}
	
	public void onClick$buttonModifica(Event event){
		modifica(false);
	}
	
	private void modifica(boolean nuovo){
		try {

			int nIndex = boxYachts.getSelectedIndex();

			if (!nuovo && nIndex == -1) { // nessuna riga selezionata

				Messagebox.show("Select a Yacht to modify", "Information", Messagebox.OK, Messagebox.INFORMATION);

			} else {
				HashMap map = new HashMap();
				if (nuovo){
					map.put("lNuovo", true);
				}
				map.put("boxYachts", boxYachts);
				Window finestraEditYacht = (Window) Executions.createComponents(
						"/editYacht.zul", null, map);
				finestraEditYacht.doModal();
			}

		} catch (SuspendNotAllowedException e) {
			e.printStackTrace();
		}
	}
	

	public class YachtsItemRenderer implements ListitemRenderer {

		public void render(Listitem li, Object data, int index) {
			new Listcell(""+((Anayacht) data).getId()).setParent(li);
			new Listcell(((Anayacht) data).getName()).setParent(li);
			new Listcell(((Anayacht) data).getCorporation()).setParent(li);
			li.setAttribute("rigaYacht", data);
			ComponentsCtrl.applyForward(li, "onDoubleClick=onDoubleClicked");
		}
	}
	
	
	
	
	
	
	// EDIT YACHT: NEW/MODIFY
	public void onCreate$windowEditYacht(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		
		boxYachts = (Listbox) args.get("boxYachts");

		if (args.containsKey("lNuovo")) {
			lNuovo = true;
		} else {
			lNuovo = false;
		}

		if (!lNuovo) {
			yachtItem = boxYachts.getSelectedItem().getAttribute("rigaYacht");
			modYacht = new AnayachtController()
					.refreshAnayacht((Anayacht) yachtItem);
			yachtItem = modYacht;
			windowEditYacht.setTitle("Ship Edit");
			name.setFocus(true);
			id.setValue(modYacht.getId());
			name.setValue(modYacht.getName());
			boatgsm.setValue(modYacht.getBoatgsm());
			corporation.setValue( modYacht.getCorporation() );
			corpid.setValue(modYacht.getCorpid());
			captain.setValue(modYacht.getCaptain());
			captgsm.setValue(modYacht.getCaptgsm());
			vesstype.setValue(modYacht.getVesstype());
			fiscalstatus.setValue(modYacht.getFiscstat());
			chiefeng.setValue(modYacht.getChiefeng());
			chiefgsm.setValue(modYacht.getChiefgsm());
			loa.setValue(modYacht.getLoa());
			loam.setValue(modYacht.getLum());
			beam.setValue(modYacht.getBeam());
			wum.setValue(modYacht.getWum());
			draft.setValue(modYacht.getDraft());
			dum.setValue(modYacht.getDum());
			grton.setValue(modYacht.getGrton());
			nettonage.setValue(modYacht.getNetton());
			fuelconnection.setValue(modYacht.getFuelconn());
			fueltankcapacity.setValue(modYacht.getFueltnkcapy());
			cum.setValue(modYacht.getCum());
			enginetype.setValue(modYacht.getEngtype());
			enginenumb.setValue(modYacht.getEngnumb());
			pumpingrate.setValue(modYacht.getPumprate());
			othercontact1.setValue(modYacht.getContact1());
			othercontact2.setValue(modYacht.getContact2());
			oilused.setValue(modYacht.getOilused());
			shipyard.setValue(modYacht.getShipyard());
			portofreg.setValue(modYacht.getPortreg());
			flag.setValue(modYacht.getFlag());
			email.setValue(modYacht.getEmail());
			satcomtel.setValue(modYacht.getSatcomtel());
			satcomfax.setValue(modYacht.getSatcomfax());
			callsign.setValue(modYacht.getCallsign());
			gsm.setValue(modYacht.getGsm());
			bank.setValue(modYacht.getBank());
			payment.setValue(modYacht.getPayment());
			//bankreceivable.setValue(modYacht.getBankpay());
			listModelList = new ListModelList();
			List<Bank> tutte_le_banche = new BankController().getBankList(null);
			listModelList.addAll(tutte_le_banche);
			bankreceivable.setModel(listModelList);
			bankreceivable.setItemRenderer(new BankItemRenderer());		
			if (modYacht.getBankpay()!=null && modYacht.getBankpay()>0){
				Bank ba = new BankController().getBankxId(modYacht.getBankpay());
				//int index = listModelList.indexOf(ba);
				//bankreceivable.setSelectedIndex(listModelList.indexOf(ba));
				for (int i = 0; i < listModelList.getSize(); i++) {
					Bank ba2 = (Bank)listModelList.get(i);
					if (ba.getId() == ba2.getId()){
						bankreceivable.setSelectedIndex(i);
					}
				}
			} else {
				bankreceivable.setSelectedIndex(-1);
			}
			
			note.setValue(modYacht.getNote());
		} else {
			windowEditYacht.setTitle("New Ship");
			name.setFocus(true);
		}

	}
	
	
	public class BankItemRenderer implements ListitemRenderer {

		public void render(Listitem li, Object data, int index) {
			new Listcell(((Bank) data).getBank()).setParent(li);
			li.setAttribute("rigaBank", data);
			ComponentsCtrl.applyForward(li, "onDoubleClick=onDoubleClicked");
		}
	}
	
	
	public void onClick$btnAnnulla(Event event){
		windowEditYacht.detach();
	}
	
	public void onClick$btnConferma(Event event){
		if (lNuovo){
			modYacht = new Anayacht();
		} else {

		}
		String testoMsg = "";
		
		modYacht.setBank(bank.getValue());
		//modYacht.setBankpay();
		modYacht.setBeam(beam.getValue());
		modYacht.setBoatgsm(boatgsm.getValue());
		//modYacht.setBroker()
		//modYacht.setBrokerid(brokerid);
		modYacht.setCallsign(callsign.getValue());
		modYacht.setCaptain(captain.getValue());
		//modYacht.setCaptainid()
		modYacht.setCaptgsm(captgsm.getValue());
		//modYacht.setCetificate()
		modYacht.setChiefeng(chiefeng.getValue());
		modYacht.setChiefgsm(chiefgsm.getValue());
		//modYacht.setCode()
		modYacht.setContact1(othercontact1.getValue());
		modYacht.setContact2(othercontact2.getValue());
		modYacht.setCorpid(corpid.getValue());
		modYacht.setCorporation(corporation.getValue());
		modYacht.setCum(cum.getValue());
		//modYacht.setDel(del);
		modYacht.setDraft(draft.getValue());
		//modYacht.setDtup(data)
		modYacht.setDum(dum.getValue());
		modYacht.setEmail(email.getValue());
		modYacht.setEngnumb(enginenumb.getValue());
		modYacht.setEngtype(enginetype.getValue());
		modYacht.setFiscstat(fiscalstatus.getValue());
		modYacht.setFlag(flag.getValue());
		modYacht.setFuelconn(fuelconnection.getValue());
		modYacht.setFueltnkcapy(fueltankcapacity.getValue());
		modYacht.setGrton(grton.getValue());
		modYacht.setGsm(gsm.getValue());
		//modYacht.setImonumber(imonumber);
		modYacht.setLoa(loa.getValue());
		modYacht.setLum(loam.getValue());
		modYacht.setName(name.getValue());
		modYacht.setNetton(nettonage.getValue());
		modYacht.setNote(note.getValue());
		modYacht.setOilused(oilused.getValue());
		modYacht.setPayment(payment.getValue());
		//modYacht.setPhoto(photo)
		modYacht.setPortreg(portofreg.getValue());
		modYacht.setPumprate(pumpingrate.getValue());
		modYacht.setSatcomfax(satcomfax.getValue());
		modYacht.setSatcomtel(satcomtel.getValue());
		modYacht.setShipyard(shipyard.getValue());
		modYacht.setVesstype(vesstype.getValue());
		modYacht.setWum(wum.getValue());
		
		if (lNuovo){
			new sisi.yacht.AnayachtController().addAnayacht(modYacht);
			testoMsg = "Adding Yacht: "+ General.trimNull( modYacht.getName() );
		} else {
			new sisi.yacht.AnayachtController().updateAnayacht(modYacht);
			testoMsg = "Updating Yacht: "+ General.trimNull( modYacht.getName() );			
		}
		
		General.showNotify( testoMsg, windowEditYacht);		
		
		//Messagebox.show("Save data...", "Information", Messagebox.OK, Messagebox.INFORMATION);
		windowEditYacht.detach();
		
		
		// aggiorna listbox
		
		if (lNuovo){
			ListModelList lml = (ListModelList) boxYachts.getListModel();
			lml.add(modYacht);
			boxYachts.setSelectedIndex(lml.indexOf(modYacht));
		} else {
			ListModelList lml = (ListModelList) boxYachts.getListModel();
			Object oYachtItem = boxYachts.getSelectedItem().getAttribute("rigaYacht");
			if (lml.indexOf(oYachtItem) == -1) {
				// non trovato... quindi non lo aggiorno
			} else {
				lml.set(lml.indexOf(oYachtItem), modYacht);
			}
		}
		
		
	}

	
	public void onClick$btnCorporation(Event event){
			Sessions.getCurrent().setAttribute("codiceCorporationSelezionato",
				"");
			HashMap map = new HashMap();
			map.put("tastoSeleziona", "S");
			map.put("idselezionato", corpid.getValue());
			Window winCorp = (Window) Executions.createComponents(
					"/corporations.zul", null, map);
			winCorp.doModal();
			String codiceSelezionato = (String) Sessions.getCurrent()
					.getAttribute("codiceCorporationSelezionato");
			if (codiceSelezionato != null && !codiceSelezionato.isEmpty()) {
				//agente.setValue(codiceSelezionato);
				Corporation corp = new CorporationController().getCorporationxId(Integer.valueOf(codiceSelezionato));
				corporation.setValue(corp.getCorpname());
				corpid.setValue(corp.getCorpid());
			}
			//nomeAgente();
	}
	
}
